﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace RPCServer.Struct
{
    abstract class PoolObject<T> where T : new()
    {
        static SyncPool<T> _pool = new(Create);

        const string IsUsedStr = "_isUsed";
        bool _isUsed;

        public PoolObject()
        {
            _isUsed = false;
        }

        static T Create()
        {
            return new();
        }

        public static T Get()
        {
            T item;
            while (true)
            {
                if (!_pool.TryTake(out item))
                {
                    item = Create();
                    break;
                }
                if (!CommolOption.GetFieldValue<bool>(item, IsUsedStr))
                {
                    CommolOption.SetFieldValue(item, IsUsedStr, true);
                    break;
                }
            }

            return item;
        }

        public static void Recycle(T item)
        {
            if (CommolOption.GetFieldValue<bool>(item, IsUsedStr))
            {
                CommolOption.SetFieldValue(item, IsUsedStr, false);
                _pool.Recycle(item);
            }
        }
    }
}
